<?php


$documentation = array(
	'README.txt' => 'com_contactform/admin/README.html'
);
renderDocumentation($documentation);

$installer_file = 'com_contactform/contactform.xml';
$installer_output = "../Installers/com_contact_v1.0.zip";
buildInstaller($installer_file, $installer_output);


function renderDocumentation($documentation, $format = 'xhtml')
{
	require 'Text/Wiki.php';
	$wiki = new Text_Wiki();
	foreach ($documentation as $source => $output)
		renderFile($wiki, $source, $output, $format);
}

function renderFile($wiki, $source, $output, $format)
{
	$sourceContents = file_get_contents($source);
	$outputContents = $wiki->transform($sourceContents, $format);
	if (($of = fopen($output, 'w+')) !== false)
	{
		fwrite($of, $outputContents);
		fclose($of);
	}
}

function appendFiles(&$files, $elements, $child, $baseDir)
{
	foreach ($elements as $group)
	{
		$folder = isset($group['folder']) ? $group['folder'] . '/' : '';
		if (isset($group->$child))
		{
			foreach ($group->$child as $file)
				$files[] = "$baseDir$folder$file";
		}
	}
}

function buildInstaller($installer_file, $installer_output)
{
	if (file_exists($installer_output))
		unlink($installer_output);

	$baseDir = dirname($installer_file) . '/';
	$files = array($installer_file);
	$root = simplexml_load_file($installer_file);
	
	appendFiles($files, $root->files, 'filename', $baseDir);
	appendFiles($files, $root->media, 'filename', $baseDir);
	appendFiles($files, $root->languages, 'language', $baseDir);

	appendFiles($files, $root->administration->files, 'filename', $baseDir);
	appendFiles($files, $root->administration->media, 'filename', $baseDir);
	appendFiles($files, $root->administration->languages, 'language', $baseDir);
	
	require 'Archive/Zip.php';
	$zip = new Archive_Zip($installer_output);
	$zip->add($files, array('remove_path' => $baseDir));
	if ($zip->errorCode() < 0)
		echo $zip->errorInfo();
}


?>
